package cn.com.sueframe.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import cn.com.sueframe.demo.vo.BaseVO;
import cn.com.sueframe.vo.PageVO;

import com.google.gson.Gson;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class BaseActionSupport extends ActionSupport implements Action {

	private static final long serialVersionUID = 1L;

	public int records;
	public Integer pageNumber;
	public Integer pageCount;
	public PrintWriter pw = null;
	public HttpSession httpSession = null;
	public HttpServletRequest servletRequest = null;
	public HttpServletResponse servletResponse = null;
	public ServletContext application = null;
	public PageVO pageVO;// 分页对象
	// 国家编码名称，"zh_CN"代表中国国家编码，“en_US”代表非中国国家
	public String countryCodeName = "CN";

	public BaseActionSupport() {
		Locale locale = Locale.getDefault();
		String country = locale.getCountry();
		countryCodeName = countryCodeName == null ? country : countryCodeName;
	}

	/**
	 * 得到当前系统语言环境
	 * 
	 * @author anmin
	 * @return String Created Apr 6, 2013
	 */
	public String getCurrentLanguage() {
		BaseVO baseVO = new BaseVO();
		String language = baseVO.getLanguage();
		if ("zh_CN".equals(language)) {
			language = "CN";
		}
		return language;
	}

	public void init() {
		servletRequest = ServletActionContext.getRequest();
		servletResponse = ServletActionContext.getResponse();
		httpSession = servletRequest.getSession();
		application = httpSession.getServletContext();
		try {
			servletResponse.setContentType("text/html;charset=UTF-8");
			servletResponse.setCharacterEncoding("UTF-8");
			servletRequest.setCharacterEncoding("UTF-8");
			pw = servletResponse.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String countryCodeName = httpSession.getAttribute("ceswich") + "";
		if (this.countryCodeName.equals(countryCodeName)) {
			httpSession.setAttribute("ceswich", this.countryCodeName);
		}
		if (countryCodeName == null) {
			httpSession.setAttribute("ceswich", this.countryCodeName);
		}
	}
	/**
	 * 得到当前登陆用户的用户账号
	 * @author anmin
	 * @return void
	 * Created May 20, 2013
	 */
	public void getCurUserName(){
	  init();
	  String userName = httpSession.getAttribute("userName") + "";
	  this.ajaxJsonResponse(userName);
	}

	/**
	 * 转换语言
	 * 
	 * @author anmin Create 2013-4-2
	 */
	public void switchLanguage() {
		countryCodeName = countryCodeName == null ? "CN" : countryCodeName;
		httpSession.setAttribute("ceswich", countryCodeName);
	}

	/**
	 * ajax响应方法
	 * 
	 * @author anmin Create 2013-3-31
	 */
	public void ajaxResponse(Object content) {
		String responseContent = "";
		if (content instanceof String) {
			responseContent = content + "";
		} else {
			responseContent = this.objToJsonString(content);
		}
		pw.write(responseContent);
		pw.close();
	}
	/**
	 * 处理系统抛出的异常信息
	 * @author anmin
	 * @return void
	 * Created Apr 22, 2013
	 */	
   public void processErrorMsg(Exception e){
    	String errorMsg = e.getMessage();
    	errorMsg = errorMsg.replaceAll("---", "<br/>---");
    	errorMsg = "SystemException:<br/> " + errorMsg;
    	this.ajaxResponse(errorMsg);
    };
	    

	/**
	 * ajax响应方法
	 * 
	 * @author anmin Create 2013-3-31
	 */
	public void ajaxJsonResponse(Object content) {
		pw.print(content);
		pw.close();
	}

	/**
	 * Object To json String
	 * 
	 * @param obj
	 * @return json String
	 * @author anmin Create 2013-3-31
	 */
	public String objToJsonString(Object obj) {

		// 初始化返回值
		String json = "";

		if (obj == null) {
			return json;
		}

		StringBuilder buff = new StringBuilder();
		Field declaredFields[] = obj.getClass().getDeclaredFields();
		Field publicFields[] = obj.getClass().getFields();

		if (declaredFields != null) {
			try {
				buff.append("[");
				buff.append("{");
				int i = 0;
				for (Field field : declaredFields) {
					if (field != null) {
						field.setAccessible(true);

						if (i != 0) {
							buff.append(",");
						}
						buff.append(field.getName());
						buff.append(":");
						buff.append("\"");
						buff.append(field.get(obj) == null ? "" : field
								.get(obj));
						buff.append("\"");
						i++;
					}

				}

				for (Field field : publicFields) {

					if (field != null) {
						if (i != 0) {
							buff.append(",");
						}
						buff.append(field.getName());
						buff.append(":");
						buff.append("\"");
						buff.append(field.get(obj) == null ? "" : field
								.get(obj));
						buff.append("\"");
						i++;
					}

				}

				buff.append("}");
				buff.append("]");
				json = buff.toString();
			} catch (Exception e) {
				throw new RuntimeException("cause:" + e.toString());
			}
		}
		json = json.replaceAll("\"", "'");
		return json;
	}

	/**
	 * 将list集合对象转变为json格式的字符串
	 * 
	 * @param listArg
	 * @author anmin Create 2013-4-6
	 */
	@SuppressWarnings("unchecked")
	public String ListToJsonString(List<Object> listArg) {
		StringBuffer jsonBuf = new StringBuffer("");
		jsonBuf.append("[");
		String tempJson = "";
		int i = 0;
		if (listArg != null && listArg.size() > 0) {
			for (Object obj : listArg) {
				tempJson = objToJsonString(obj);
				tempJson = tempJson == null ? "" : tempJson;
				if (!"".equals(tempJson)) {
					tempJson = tempJson.substring(1, tempJson.lastIndexOf("]"));
					tempJson = tempJson.replaceAll("\"", "'");
				}
				if (i != listArg.size() - 1) {
					tempJson += ",";
				}
				jsonBuf.append(tempJson);
				i++;
			}
		}
		jsonBuf.append("]");
		return jsonBuf.toString();
	}
	/**
	 * 初始化用户信息
	 * @author anmin
	 * @return void
	 * Created May 12, 2013
	 */
	public void initUserInfo(String userName,String userPassword){
		httpSession.setAttribute("userName", userName);
		httpSession.setAttribute("userPassword", userPassword);
	}
	//added by anner begin
	/**
	 * ajax响应方法,返回json字符串
	 * 
	 * @author anmin Create 2013-3-31
	 */
	public void ajaxResponseJsonString(Object content) {
		String responseContent = "";
		if (content instanceof String) {
			responseContent = content + "";
		} else {
			responseContent = this.objToJsonByGsonTool(content);
		}
		pw.write(responseContent);
		pw.close();
	}
	
	/**
	 * 通过工具将对象转化成json字符串
	 * 
	 * @author anler
	 * @return String
	 * Created Jul 25, 2013
	 */
	public String objToJsonByGsonTool(Object obj){
		// 初始化返回值
		String json = "";

		if (obj == null) {
			return json;
		}
		Gson gson = new Gson();
		json = gson.toJson(obj);
		return json;
	}

	
	//added by anner end
	

    /**
     * 清除登陆用户信息
     * @author anmin
     * @return void
     * Created May 28, 2013
     */	
	public void clearUserInfo(){
		httpSession.setAttribute("userName", null);
		httpSession.setAttribute("userPassword", null);
	}

	public String getCountryCodeName() {
		return countryCodeName;
	}

	public void setCountryCodeName(String countryCodeName) {
		this.countryCodeName = countryCodeName;
	}

	public PageVO getPageVO() {
		return pageVO;
	}

	public void setPageVO(PageVO pageVO) {
		this.pageVO = pageVO;
	}

}
